package com.team.easybuy.util;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.factory.Factory.Payment;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yan
 * @date 2022-06-28 10:54:40
 * @description
 */
@ConfigurationProperties(prefix = "alipay")
@Component
public class AliPayUtil {
    private String protocol;
    private String gatewayHost;
    private String signType;
    //请填写您的AppId，例如：2019091767145019
    private String appId;
    // 请填写您的应用私钥，例如：MIIEvQIBADANB ... ...
    private String merchantPrivateKey;
    // 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt
    private String merchantCertPath;
    //请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt
    private String alipayCertPath;
    //请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt
    private String alipayRootCertPath;
    //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
    private String alipayPublicKey;
    //可设置异步通知接收服务地址（可选）
    private String notifyUrl;
    //可设置AES密钥，调用AES加解密相关接口时需要（可选）
    private String encryptKey;
    //可设置同步通知接收服务地址
    private String returnUrl;

    public String toPCPay(String subject, String outTradeNo, String totalAmount) throws Exception {
        String result = "";
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions());
        try {
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradePagePayResponse response = Payment.Page().pay(subject, outTradeNo, totalAmount, returnUrl);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                result = response.body;
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + response.body);
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return result;
    }

    //验签,判断数据是不是来自支付宝
    public boolean validateSign(Map<String, String> paramster) throws Exception {
        boolean flag = Factory.Payment.Common().verifyNotify(paramster);
        return flag;
    }

    public String refund(String outTradeNo, String refundAmount) {
        String result = "";
        Factory.setOptions(getOptions());
        try {
            AlipayTradeRefundResponse refund = Payment.Common().refund(outTradeNo, refundAmount);
            if (ResponseChecker.success(refund)) {
                result = refund.getHttpBody();
                System.out.println("调用成功");
            } else {
                System.err.println("调用失败，原因：" + refund.getHttpBody());
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
        }
        return result;
    }


    private Config getOptions() {
        Config config = new Config();
        config.protocol = getProtocol();
        config.gatewayHost = getGatewayHost();
        config.signType = getSignType();
        config.appId = getAppId();
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        config.merchantPrivateKey = getMerchantPrivateKey();
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        config.alipayPublicKey = getAlipayPublicKey();
        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = getNotifyUrl();
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = getEncryptKey();
        return config;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getGatewayHost() {
        return gatewayHost;
    }

    public void setGatewayHost(String gatewayHost) {
        this.gatewayHost = gatewayHost;
    }

    public String getSignType() {
        return signType;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getMerchantPrivateKey() {
        return merchantPrivateKey;
    }

    public void setMerchantPrivateKey(String merchantPrivateKey) {
        this.merchantPrivateKey = merchantPrivateKey;
    }

    public String getAlipayPublicKey() {
        return alipayPublicKey;
    }

    public void setAlipayPublicKey(String alipayPublicKey) {
        this.alipayPublicKey = alipayPublicKey;
    }

    public String getNotifyUrl() {
        return notifyUrl;
    }

    public void setNotifyUrl(String notifyUrl) {
        this.notifyUrl = notifyUrl;
    }

    public String getEncryptKey() {
        return encryptKey;
    }

    public void setEncryptKey(String encryptKey) {
        this.encryptKey = encryptKey;
    }

    public String getReturnUrl() {
        return returnUrl;
    }

    public void setReturnUrl(String returnUrl) {
        this.returnUrl = returnUrl;
    }
}
